package com.stars.easyms.datasource.mybatis;

import lombok.Getter;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.lang.NonNull;
import org.springframework.transaction.support.ResourceHolderSupport;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static org.springframework.util.Assert.notNull;

/**
 * <p>className: EasyMsSqlSessionHolder</p>
 * <p>description: EasyMs自定义sqlSession的holder类</p>
 *
 * @author guoguifang
 * @date 2020-01-08 18:14
 * @since 1.4.2
 */
public final class EasyMsSqlSessionHolder extends ResourceHolderSupport {

    private final Map<SqlSessionFactory, SqlSession> sqlSessionMap;

    @Getter
    private final ExecutorType executorType;

    @Getter
    private final PersistenceExceptionTranslator persistenceExceptionTranslator;

    EasyMsSqlSessionHolder(@NonNull SqlSessionFactory sessionFactory, SqlSession sqlSession,
                           ExecutorType executorType,
                           PersistenceExceptionTranslator persistenceExceptionTranslator) {

        notNull(sqlSession, "SqlSession must not be null");
        notNull(executorType, "ExecutorType must not be null");

        this.sqlSessionMap = new ConcurrentHashMap<>(8);
        this.sqlSessionMap.put(sessionFactory, sqlSession);
        this.executorType = executorType;
        this.persistenceExceptionTranslator = persistenceExceptionTranslator;
    }

    public SqlSession getSqlSession(@NonNull SqlSessionFactory sqlSessionFactory) {
        return sqlSessionMap.get(sqlSessionFactory);
    }

    void setSqlSession(@NonNull SqlSessionFactory sessionFactory, SqlSession sqlSession) {
        this.sqlSessionMap.put(sessionFactory, sqlSession);
    }

    Collection<SqlSession> getSqlSessionSet() {
        return Collections.unmodifiableCollection(sqlSessionMap.values());
    }
}